package com.ltxtiyu.video.tool;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.*;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class ApiTool {
	
	private static final String WX_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=SECRET";
	
	public static String post(Map<String, String> paramMap, String url) {
		
		HttpClient httpclient = new DefaultHttpClient();
		String result = "";
		
		try {
			HttpPost httpPost = new HttpPost(url);
			List<NameValuePair> nvps = getParamList(paramMap);
            System.out.println(nvps.toString());
            UrlEncodedFormEntity uefe = new UrlEncodedFormEntity(nvps, "GBK");
			httpPost.setEntity(uefe);
			HttpResponse response = httpclient.execute(httpPost);
			
			HttpEntity entity = response.getEntity();
			
			if (entity != null) {
				String rpString = EntityUtils.toString(entity, "GBK");
				result += rpString;
				System.out.println(new String(result.getBytes(), "GBK"));
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally{
			 httpclient.getConnectionManager().shutdown();
		}
		
		return result;
	}
	
	public static JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr) {
		JSONObject jsonObject = null;
		StringBuffer buffer = new StringBuffer();
		try {
			// 创建SSLContext对象，并使用我们指定的信任管理器初始化
			TrustManager[] tm = { new X509TrustManager() {

				public X509Certificate[] getAcceptedIssuers() {
					return null;
				}

				public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {

				}

				public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {

				}
			} };
			SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
			sslContext.init(null, tm, new java.security.SecureRandom());
			// 从上述SSLContext对象中得到SSLSocketFactory对象
			SSLSocketFactory ssf = sslContext.getSocketFactory();

			URL url = new URL(requestUrl);
			HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
			httpUrlConn.setSSLSocketFactory(ssf);

			httpUrlConn.setDoOutput(true);
			httpUrlConn.setDoInput(true);
			httpUrlConn.setUseCaches(false);
			// 设置请求方式（GET/POST）
			httpUrlConn.setRequestMethod(requestMethod);

			if ("GET".equalsIgnoreCase(requestMethod)) {
				httpUrlConn.connect();
			}
			// 当有数据需要提交时
			if (null != outputStr) {
				OutputStream outputStream = httpUrlConn.getOutputStream();
				// 注意编码格式，防止中文乱码
				outputStream.write(outputStr.getBytes("UTF-8"));
				outputStream.close();
			}

			// 将返回的输入流转换成字符串
			InputStream inputStream = httpUrlConn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

			String str = null;
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			bufferedReader.close();
			inputStreamReader.close();
			// 释放资源
			inputStream.close();
			inputStream = null;
			httpUrlConn.disconnect();
			jsonObject = JSONObject.parseObject(buffer.toString());
		} catch (Exception e) {
		}
		return jsonObject;
	}
	
	private static List<NameValuePair> getParamList(Map<String, String> paramMap){
		List<NameValuePair> result = new ArrayList<NameValuePair>();
		for(Entry<String, String> e : paramMap.entrySet()){
			result.add(new BasicNameValuePair(e.getKey(), e.getValue()));
		}
		return result;
	}
	
	public static String getAccessToken(String appId, String secret) {

		String url = WX_TOKEN_URL;
		String tokenUrl = url.replace("APPID", appId).replace("SECRET", secret);
		JSONObject resultJson = ApiTool.httpsRequest(tokenUrl, "GET", null);
		String token = resultJson.getString("access_token");
		return token;
	}
}
